package com.ysd.twocrm.config;

import com.ysd.twocrm.token.CheckResult;
import com.ysd.twocrm.token.JwtUtils;
import com.ysd.twocrm.token.R;
import com.ysd.twocrm.token.SystemConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


//拦截器

public class SysInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(SysInterceptor.class);

    public void print(HttpServletResponse response, Object message) {
        try {
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            PrintWriter writer = response.getWriter();
            writer.write(message.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //System.out.println("我开始访问");
        //	StringBuffer requestURL = request.getRequestURL();
        //System.out.println(requestURL+">="+"我是协议");
        // instanceof是Java中的二元运算符，左边是对象，右边是类；当对象是右边类或子类所创建对象时，返回true；否则，返回false。
        if (handler instanceof HandlerMethod) {
         //   System.out.println("我进来了>=====================");
            String authHeader = request.getHeader("token");
            // isEmpty是否为空
            if (StringUtils.isEmpty(authHeader)) {
                logger.info("验证失败");
                print(response, R.error(SystemConstant.JWT_ERRCODE_NULL, "签名验证不存在"));
                return false;
            } else {
                // 验证jwt的签名，返回checkresult对象
                CheckResult checkresult = JwtUtils.validateJWT(authHeader);
                if (checkresult.isSuccess()) {
                    return true;
                } else {
                    switch (checkresult.getErrCode()) {
                        // 签名验证不通过
                        case SystemConstant.JWT_ERRCODE_FAIL:
                            logger.info("签名验证不通过");
                            print(response, R.error(checkresult.getErrCode(), "签名验证不同个"));
                            break;
                        // 签名过期，返回过期提示吗
                        case SystemConstant.JWT_ERRCODE_EXPIRE:
                            logger.info("签名过期");
                            print(response, R.error(checkresult.getErrCode(), "签名过期"));
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            }
        } else {
        //    System.out.println("我出去了>=====================");
            return true;
        }

    }

    /**
     * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后，也就是DispatcherServlet渲染了视图执行，
     * 这个方法的主要作用是用于清理资源的，当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。
     */

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
